package cn.mesmile.pdf.controller;

import cn.hutool.core.date.DateUtil;
import cn.mesmile.pdf.entity.Student;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.sun.deploy.net.URLEncoder;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;

/**
 * @author zb
 * @date 2021/3/7 11:31
 * @Description:
 */
@Slf4j
@RequestMapping("/api/v1/pdf")
@RestController
public class PDFController {


    @GetMapping("/download")
    public void exportPdf(HttpServletResponse response){

        Student student = new Student();
        student.setUsername("学生姓名");
        student.setAge(20);
        student.setBirthday(DateUtil.parseDate("2020-03-15"));
        student.setDescription("Java是一门面向对象编程语言，不仅吸收了C++语言的各种优点，还摒弃了C++里难以理解的多继承、指针等概念，因此Java语言具有功能强大和简单易用两个特征。Java语言作为静态面向对象编程语言的代表，极好地实现了面向对象理论，允许程序员以优雅的思维方式进行复杂的编程 [1]  。");
        student.setEducation("本科");


        String filename = "学生信息表.pdf";
        // 1.指定解析器
        System.setProperty("javax.xml.parsers.DocumentBuilderFactory",
                "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
        String file;
        String path = Thread.currentThread().getContextClassLoader().getResource("").getPath()+"static";

        OutputStream os = null;
        PdfStamper ps = null;
        PdfReader reader = null;
        try {
            response.setContentType("application/pdf");
            response.setHeader("Content-Disposition", "attachment;fileName="+ URLEncoder.encode(DateUtil.now()+"——"+filename, "UTF-8"));
            os = response.getOutputStream();
            // 2 读入pdf表单
            reader = new PdfReader(path+ "/"+filename);
            // 3 根据表单生成一个新的pdf
            ps = new PdfStamper(reader, os);
            // 4 获取pdf表单
            AcroFields form = ps.getAcroFields();
            // 5给表单添加中文字体 这里采用系统字体。不设置的话，中文可能无法显示
            BaseFont bf = BaseFont.createFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);

            form.addSubstitutionFont(bf);
            // 6查询数据================================================
            Map<String, String> data = new HashMap<String, String>();
            data.put("username", student.getUsername());
            data.put("age", student.getAge().toString());
            data.put("birthday", DateUtil.formatDate(student.getBirthday()));
            data.put("description", student.getDescription());
            data.put("education", student.getEducation());


            // 7遍历data 给pdf表单表格赋值
            for (String key : data.keySet()) {
                form.setField(key,data.get(key).toString());
            }
            ps.setFormFlattening(true);
            log.info("*******************PDF导出成功***********************");
        } catch (Exception e) {
            log.error("*******************PDF导出失败***********************");
            e.printStackTrace();
        } finally {
            try {
                if (ps!= null){
                    ps.close();
                }
                if (reader != null) {
                    reader.close();
                }
                if (os != null) {
                    os.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


}
